package com.senseauto.mediamuxerdemo.muxer;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


import com.senseauto.mediamuxerdemo.AutoApplication;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 文件处理工具类
 */
public class FileUtils {

    private static final String TAG = "FileUtils";


    private static final String MAIN_DIR_NAME = "/android_records";
    private static final String BASE_VIDEO = "/video/";
    private static final String BASE_EXT = ".mp4";

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm");
    private String currentFileName = "-";
    private String nextFileName;

    public FileUtils() {
    }

    public static File getOutputMediaFile(Context context, int frame) {
        File mediaStorageDir = context.getExternalFilesDir("frame");;
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.

        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }

        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINESE).format(new Date());
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "image_" + frame + ".jpg");

        return mediaFile;
    }

    public static String getVideoFilePath8295(Context context, int cameraId, long timestamp) {
        // Get the base directory: /data/user/0/com.senseauto.datacollectapp/files/
        final File dir = context.getFilesDir();

        // Format the timestamp for the subdirectory (YYYYMMddHHmmss)
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss", Locale.CHINA);
        String timestampStr = format.format(new Date(timestamp));

        // Create the subdirectory: /data/user/0/com.senseauto.datacollectapp/files/YYYYMMddHHmmss/
        File subDir = new File(dir, timestampStr);
        if (!subDir.exists()) {
            subDir.mkdirs(); // Create the directory if it doesn't exist
        }

        // Create the file path: /data/user/0/com.senseauto.datacollectapp/files/YYYYMMddHHmmss/Camera_{cameraId}_video_{timestamp}.mp4
        File file = new File(subDir, "Camera_" + cameraId + "_video_" + timestampStr + ".mp4");

        // Log the file path
        Log.e(TAG, "视频保存路径：" + file.getAbsolutePath());

        return file.getAbsolutePath();
    }


    public boolean requestSwapFile() {
        return false;
//        return requestSwapFile(false);
    }

    public boolean hasNextFileName;

    public void setNextFileName(String path){
        if (!TextUtils.isEmpty(path)){
            nextFileName = path;
            hasNextFileName = true;
        }
    }

    public boolean requestSwapFile(boolean force) {
        if (hasNextFileName){
            hasNextFileName = false;
            return true;
        }
        //SD 卡可读写
        String fileName = getFileName();
        boolean isChanged = false;

        if (!currentFileName.equalsIgnoreCase(fileName)) {
            isChanged = true;
        }

        if (isChanged || force) {
            nextFileName = getSaveFilePath(fileName);
            return true;
        }

        return false;
    }

    public String getNextFileName() {
        return nextFileName;
    }

    private String getFileName() {
        String format = simpleDateFormat.format(System.currentTimeMillis());
        return format;
    }

    private String getSaveFilePath(String fileName) {
        currentFileName = fileName;

        String string = getVideoFilePath(AutoApplication.getContext());
        File file = new File(string);
        File parentFile = file.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        return string;
    }

    /**
     * 检查剩余空间
     */
    private void checkSpace() {
        StringBuilder fullPath = new StringBuilder();
        String checkPath = getVideoFilePath(AutoApplication.getContext());
        fullPath.append(checkPath);
        fullPath.append(MAIN_DIR_NAME);
        fullPath.append(BASE_VIDEO);

        if (checkCardSpace(checkPath)) {
            File file = new File(fullPath.toString());

            if (!file.exists()) {
                file.mkdirs();
            }

            String[] fileNames = file.list();
            if (fileNames.length < 1) {
                return;
            }

            List<String> fileNameLists = Arrays.asList(fileNames);
            Collections.sort(fileNameLists);

            for (int i = 0; i < fileNameLists.size() && checkCardSpace(checkPath); i++) {
                //清理视频
                String removeFileName = fileNameLists.get(i);
                File removeFile = new File(file, removeFileName);
                try {
                    removeFile.delete();
                    Log.e("angcyo-->", "删除文件 " + removeFile.getAbsolutePath());
                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("angcyo-->", "删除文件失败 " + removeFile.getAbsolutePath());
                }
            }
        }
    }

    private boolean checkCardSpace(String filePath) {
        File dir = new File(filePath);
        double totalSpace = dir.getTotalSpace();//总大小
        double freeSpace = dir.getFreeSpace();//剩余大小
        if (freeSpace < totalSpace * 0.2) {
            return true;
        }
        return false;
    }

    /**
     * 获取sdcard路径
     */
    public static String getExternalStorageDirectory() {
        return Environment.getExternalStorageDirectory().getPath();
    }

    private String getVideoFilePath(Context context) {
        final File dir = context.getExternalFilesDir(null);
        return (dir == null ? "" : (dir.getAbsolutePath() + "/"))
                + System.currentTimeMillis() + ".mp4";
    }

}
